<script setup>
import {defineProps, defineEmits} from 'vue';

// 定义 Props
const props = defineProps({
  data: {
    type: Array,
    required: true,
  },
  depth: {
    type: Number,
    default: 0, // 默认深度为 0
  },
});

// 定义 Emits
const emit = defineEmits(['click']);

// 切换节点展开/折叠状态
const toggleExpand = (node) => {
  node.expanded = !node.expanded;
};
</script>
<template>
  <div class="zdp-tree">
    <ul v-if="data.length" class="zdp-tree__list">
      <li v-for="(node, index) in data" :key="index" class="zdp-tree__node">
        <!-- 节点内容 -->
        <div
            :class="['zdp-tree__node-content', { 'zdp-tree__node-content--folder': node.children }]"
            :style="{ paddingLeft: `${depth * 10}px` }"
            @click="emit('click', node)"
        >
          <div @click="toggleExpand(node)">
            <!-- 节点图标 -->
            <span class="zdp-tree__node-icon">
            <svg
                v-if="node.children"
                class="zdp-tree__node-icon"
                viewBox="0 0 24 24"
                width="16"
                height="16"
            >
              <path
                  fill="currentColor"
                  d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z"
              />
            </svg>
            <svg
                v-else
                class="zdp-tree__node-icon"
                viewBox="0 0 24 24"
                width="16"
                height="16"
            >
              <path
                  fill="currentColor"
                  d="M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6zM6 20V4h7v5h5v11H6z"
              />
            </svg>
          </span>
            <!-- 节点名称 -->
            <span class="zdp-tree__node-label">{{ node.label }}</span>
          </div>
        </div>

        <!-- 递归渲染子节点 -->
        <Tree
            v-if="node.children && node.expanded"
            :data="node.children"
            :depth="depth + 1"
            @click="emit('click', node)"
        />
      </li>
    </ul>
  </div>
</template>


<style scoped>
.zdp-tree {
  font-family: Arial, sans-serif;
  color: #333;
}

.zdp-tree__list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.zdp-tree__node {
  margin: 4px 0;
}

.zdp-tree__node-content {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.zdp-tree__node-content:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.zdp-tree__node-content--folder {
  font-weight: bold;
  color: #409eff;
}

.zdp-tree__node-icon {
  margin-right: 3px;
  color: #409eff;
  transition: transform 0.3s ease;
}

.zdp-tree__node-icon--expanded {
  transform: rotate(90deg);
}

.zdp-tree__node-label {
  flex: 1;
}
</style>